package org.lemon.transport.context.service.queue.rabbit;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.Gson;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;
import org.lemon.transport.context.service.queue.QueueAdmin;
import org.lemon.transport.context.service.queue.QueueCallback;
import org.lemon.transport.context.service.queue.QueueProducer;
import org.lemon.transport.context.service.queue.TopicPartitionInfo;
import org.lemon.transport.context.data.queue.message.DefaultQueueMessage;
import org.lemon.transport.context.data.queue.message.QueueMessage;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

@Slf4j
public class RabbitMqProducerTemplate<T extends QueueMessage> implements QueueProducer<T> {

    private final String defaultTopic;
    private final Gson gson = new Gson();
    private final QueueAdmin admin;
    private final RabbitMqSettings rabbitMqSettings;
    private final ListeningExecutorService producerExecutor;
    private final Channel channel;
    private final Connection connection;

    private final Set<TopicPartitionInfo> topics = ConcurrentHashMap.newKeySet();

    public RabbitMqProducerTemplate(QueueAdmin admin, RabbitMqSettings rabbitMqSettings, String defaultTopic) {

        this.admin = admin;
        this.defaultTopic = defaultTopic;
        this.rabbitMqSettings = rabbitMqSettings;
        this.producerExecutor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        try {
            this.connection = rabbitMqSettings.getConnectionFactory().newConnection();
        } catch (IOException | TimeoutException e) {
            log.error("Failed to created connection.", e);
            throw new RuntimeException("Failed to created connection.", e);
        }
        try {
            this.channel = connection.createChannel();
        } catch (IOException e) {
            log.error("Failed to created channel.", e);
            throw new RuntimeException("Failed to created channel.", e);
        }
    }

    @Override
    public void init() {

    }

    @Override
    public String getDefaultTopic() {
        return this.defaultTopic;
    }

    @Override
    public void send(TopicPartitionInfo topic, QueueMessage msg, QueueCallback callback) {

        createTopicIfNotExist(topic);
        AMQP.BasicProperties properties = new AMQP.BasicProperties();
        DefaultQueueMessage message = new DefaultQueueMessage(msg);
        try {
            channel.basicPublish(rabbitMqSettings.getExchangeName(), topic.getFullTopicName(), properties, gson.toJson(message).getBytes());
            if (callback != null) {
                callback.onSuccess();
            }
        } catch (IOException e) {
            log.error("Failed publish message: [{}].", msg, e);
            if (callback != null) {
                callback.onFailure(e);
            }
        }
    }

    @Override
    public void stop() {

        if (producerExecutor != null) {
            producerExecutor.shutdownNow();
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                log.error("Failed to close the channel.", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                log.error("Failed to close the connection.", e);
            }
        }
    }

    private void createTopicIfNotExist(TopicPartitionInfo topic) {
        if (topics.contains(topic)) {
            return;
        }
        admin.createTopicIfNotExists(topic.getFullTopicName());
        topics.add(topic);
    }
}
